package com.jsmtr.rms.controller;

import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.utils.DateTools;
import com.jsmtr.rms.utils.PhoneTools;
import com.jsmtr.rms.utils.StringTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.entity.vo.ZZUserForm;
import com.jsmtr.rms.service.IRecommendService;
import com.jsmtr.rms.service.IDoZZService;
import com.jsmtr.rms.service.ISchoolService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.EnumTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Do/ZZPReview")
public class DoZZPReviewController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IRecommendService recommendService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    private IDoZZService doZZService;


    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);

            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);

            //状态
            List states=new ArrayList();
            List stateList=utilService.groupZZStateByFid(fid,"背景调查");
            if (stateList!=null&&stateList.size()>0){
                states.addAll(stateList);
            }else{
                states.add("未处理");
            }
            model.addAttribute("states",states);

            List<BaseConfig> _configs = utilService.getConfigs("dxmb");
            StringBuilder strs = new StringBuilder();
            for (BaseConfig _config : _configs) {
                strs.append("<option value='" + _config.getCode() + "'>" + _config.getName() + "</option>");
            }
            model.addAttribute("dxmb", strs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/PReview/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom")==null?"":request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto")==null?"":request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom")==null?"":request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto")==null?"":request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("graduationyear")==null?"":request.getParameter("graduationyear").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            _map.put("scorearea", request.getParameter("scorearea"));
            Map<String, Object> map = recommendService.getUserMap(page, perpage, user,_map);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                int num = 0;
                for (HashMap<String,Object> _user :  object) {
                    result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user.get("ID") + "' id='cb_" + _user.get("ID") + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/UserResume/ViewDResume?id="
                            + _user.get("DRID") + "'>" + _user.get("NAME")
                            + "</a></td>");//简历ID和HRZZUser的ID相同
                    result.append("<td>" + _user.get("GENDER") + "</td>");
                    result.append("<td>" + _user.get("CODE") + "</td>");
                    result.append("<td>" + _user.get("MAJOR") + "</td>");
                    result.append("<td>" + _user.get("GRADUATIONTIME") + "</td>");
                    result.append("<td>" + _user.get("TEL") + "</td>");
                    result.append("<td>" + _user.get("JOB") + "<input type='hidden' name='user[" + num + "].id' value='" + _user.get("ID") + "' /></td>");
                    result.append("<td>" + _user.get("POINT") + "</td>");
                    result.append("<td>" + _user.get("MSSTATE") + "</td>");

                    result.append("<td>"+_user.get("ZSSTATE")+"</td>");
                    /*result.append("<td><div><select name='user[" + num + "].zsstate'>");
                    result.append("<option value='未背景调查'>未背景调查</option><option value='已通过'>已通过</option><option value='未通过'>未通过</option>");
                    result.append("</select><input type='hidden' value='" + _user.get("Zsstate") + "' /></div></td>");*/
                    /*result.append("<td><div><input type='text' name='user[" + num + "].zsremark' value='" + (_user.get("Zsremark") == null ? "" : _user.get("Zsremark")) + "' /></div></td>");*/
                    if(_user.get("ZSREMARK")==null){
                        result.append("<td></td>");
                    }else{
                        result.append("<td>"+_user.get("ZSREMARK")+"</td>");
                    }

                    if (_user.get("OP4").equals("未公布")) {
                        result.append("<td class='true'><span>" + _user.get("OP4") + "</span></td>");
                    } else {
                        result.append("<td class='false'><span>" + _user.get("OP4") + "</span></td>");
                    }

                    result.append("<td>");
                    if (_user.get("FQSTATE").equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        // result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                        result.append("<span class='layui-badge layui-bg-gray' title='已放弃'>弃</span>");
                    } else {
                        if (_user.get("ZSSTATE") == null) {
                            //result.append("<td class='true'><span>未完成</td></tr>");
                            result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                        } else {
                            if (_user.get("ZSSTATE").equals("未通过")||_user.get("ZSSTATE").equals("不通过")||_user.get("ZSSTATE").equals("不合格")||_user.get("ZSSTATE").equals("未合格")) {
                                result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                                //result.append("<td class='false'><span>已完成</td></tr>");
                            } else {
                                boolean bl = _user.get("FID").equals(flowid);
                                if (bl){
                                    result.append("<span class='layui-badge layui-bg-orange' title='未完成'>未</span>");
                                }else{
                                    result.append("<span class='layui-badge layui-bg-green' title='已完成'>完</span>");
                                }
                            }
                        }
                    }
                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        result.append("<span class='layui-badge layui-bg-blue' title='转岗(原岗位:"+_user.get("NJNAME")+")'>岗</span>");
                    }
                    result.append("</td>");
                    result.append("</tr>");

                    num++;
                }
            } else {
                result.append("<tr><td colspan='18'>未找到符合条件的数据</td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='14'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]

    @ResponseBody
    @RequestMapping(value = "/getZzPreviewListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getZzPreviewListLayuiJson(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom")==null?"":request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto")==null?"":request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom")==null?"":request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto")==null?"":request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("graduationyear")==null?"":request.getParameter("graduationyear").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            _map.put("scorearea", request.getParameter("scorearea"));
            Map<String, Object> map = recommendService.getUserMap(page, limit, user,_map);

            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            JSONArray jsonArray = new JSONArray();
            int num = 1;

            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                for (HashMap<String,Object> _user :  object) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("id_cb", "cb_" + _user.get("ID"));
                    jsonObject.put("id", limit * (page - 1) + num);
                    jsonObject.put("NAME", _user.get("NAME"));
                    jsonObject.put("ContextPath", request.getContextPath() + "/UserResume/ViewDResume?id=" + _user.get("DRID"));
                    jsonObject.put("SEXNAME", _user.get("GENDER"));
                    jsonObject.put("CARDNO", _user.get("CODE"));
                    jsonObject.put("MAJORNAME", (_user.get("MAJOR") == null ? "" : _user.get("MAJOR")));
                    jsonObject.put("JOB",  (_user.get("JOB") == null ? "" : _user.get("JOB")));
                    jsonObject.put("GRADUATIONTIME", (_user.get("GRADUATIONTIME") == null ? "" : _user.get("GRADUATIONTIME")));
                    jsonObject.put("TEL", _user.get("TEL"));
                    jsonObject.put("ZSSTATE", (_user.get("ZSSTATE") == null ? "" : _user.get("ZSSTATE")));
                    jsonObject.put("MID", _user.get("MID"));
                    jsonObject.put("MCONTENT", (_user.get("MCONTENT") == null ? "" : _user.get("MCONTENT")));
                    jsonObject.put("ZSREMARK", (_user.get("ZSREMARK") == null ? "" : _user.get("ZSREMARK")));

                    jsonObject.put("STATEb", _user.get("OP4"));

                    jsonObject.put("FQSTATE", _user.get("FQSTATE"));
                    jsonObject.put("FID", _user.get("FID"));
                    jsonObject.put("NRID", _user.get("NRID"));
                    jsonObject.put("NJNAME", _user.get("NJNAME"));

                    if (_user.get("FQSTATE").equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        jsonObject.put("STATEc", "弃");
                    } else {
                        if (_user.get("ZSSTATE") == null) {
                            jsonObject.put("STATEc", "未");
                        } else {
                            if (_user.get("ZSSTATE").equals("未通过")||_user.get("ZSSTATE").equals("不通过")||_user.get("ZSSTATE").equals("不合格")||_user.get("ZSSTATE").equals("未合格")) {
                                jsonObject.put("STATEc", "完");
                            } else {
                                boolean bl = _user.get("FID").equals(flowid);
                                if (bl){
                                    jsonObject.put("STATEc", "未");
                                }else{
                                    jsonObject.put("STATEc", "完");
                                }
                            }
                        }
                    }

                    if (StringTools.trimNotEmpty(_user.get("NRID"))){
                        jsonObject.put("NJNAME", _user.get("NJNAME"));
                        jsonObject.put("STATEd", _user.get("岗"));
                    }else
                        jsonObject.put("NRID", "");

                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);
            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }
            //[start] 提交背景调查结果

    @RequestMapping(value = "/RAction", method = RequestMethod.POST)
    public void RAction(HttpServletRequest request, HttpServletResponse response, ZZUserForm users) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            String pid =request.getParameter("pid");
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择参加背景调查的应聘者!", "no", response);
            }
            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    Date time = new Date();
                    List<HRZZUser> editlist = new ArrayList<HRZZUser>();
                    String zsstate=request.getParameter("zsstate");
                    String zsremark=request.getParameter("zsremark");
                   /* for (HRZZUser user : users.getUser()) {
                        HRZZUser usr = recommendService.getViewUser(user.getId());*/
                    for (String uid : uids) {
                        HRZZUser usr = recommendService.getViewUser(uid);
                        if (usr.getDeptcode().equals(cuser.getUdept())
                                && usr.getFqstate().equals("未放弃")
                                && usr.getFid().equals(fid)) {
                            //usr.setZsstate(user.getZsstate());
                            //usr.setZsremark(user.getZsremark());
                            usr.setZsstate(zsstate);
                            usr.setZsremark(zsremark);

                            usr.setZsdate(time);
                            usr.setZsuid(cuser.getId());
                            usr.setZsuname(cuser.getUname());

                            editlist.add(usr);
                        }
                    }
                    if (editlist.size() > 0) {
                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前信息不支持次操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    @RequestMapping(value = "/MsgAction", method = RequestMethod.POST)
    public void MsgAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] uids = request.getParameterValues("uid");
            if (uids == null) {
                utilService.printJsonResult(false, "请选择参加背景调查的应聘者!", "no", response);
            } else {
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码

                BaseUser cuser = utilService.getSessionUser(request);
                if (cuser.getUdept().equals(deptcode)) {
                    //流程是否结束
                    if (utilService.FlowIsDoing(fid)) {
                        //List<DUserResume> editlist = new ArrayList<DUserResume>();
                        List<HRZZUser> editlist = new ArrayList<HRZZUser>();
                        String dxnr = request.getParameter("dxnr").trim();

                        List<Map<String, String>> msgs = new ArrayList<Map<String, String>>();
                        List<HRZZUser> users = doZZService.getUsers(uids);
                       /* List<DUserResume> users = doZZService.getResumes(uids);*/

                       // for (DUserResume user : users) {
                        for (HRZZUser user : users) {
                            if (user.getFid().equals(fid) && user.getFqstate().equals("未放弃")) {
                                user.setBjmsg("已发通知");
                                editlist.add(user);

                                //-------------短信----------------
                                Map<String, String> _map = new HashMap<String, String>();
                                _map.put("tel", user.getTel());
                                if(dxnr.indexOf("{姓名}")>0){
                                    _map.put("cont", dxnr.replace("{姓名}", user.getName()).replace("{已通过}", user.getZsstate()));
                                }else{
                                    _map.put("cont", dxnr);
                                }
                                msgs.add(_map);
                            }
                        }
                        if (editlist.size() > 0) {
                            utilService.editList(editlist);
                            BaseMessageConfig messageConfig=utilService.getMessageConfig();
                            //发送短信
                            if (PhoneTools.sendMsg(msgs,messageConfig.getUsername(),messageConfig.getPassword(),messageConfig.getHost())) {
                                utilService.printJsonResult(true, "操作成功！", "no", response);
                            } else {
                                utilService.printJsonResult(false, "短信发送失败！", "no", response);
                            }
                        } else {
                            utilService.printJsonResult(false, "当前信息不能执行此操作！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    List editlist = new ArrayList();
                    List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                    ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                    for (HRZZUser user : users) {
                        if (user.getFid().equals(fid)&& user.getFqstate().equals("未放弃")) {
                            if(user.getZsstate().equals("已通过")||user.getZsstate().equals("通过")||user.getZsstate().equals("合格")){
                                user.setFid(nFlow.getId());
                                user.setPath(user.getPath() + nFlow.getId() + "/");
                                editlist.add(user);
                            }
                        }
                    }

                    if (editlist.size() > 0) {
                        nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                        editlist.add(nFlow);

                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
